import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../utils/http.dart';

// 头部组件
class LoginHeader extends StatelessWidget {
  const LoginHeader({Key? key, this.name}) : super(key: key);
  final name;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Align(
            alignment: Alignment.centerRight,
            child: FractionallySizedBox(
              widthFactor: 0.5,
              child: Image.asset('assets/img/ellipse.png',
                  width: double.infinity, fit: BoxFit.cover),
            )),
        SafeArea(
          child: Column(
            textDirection: TextDirection.ltr,
            children: [
              Align(
                  alignment: Alignment.centerRight,
                  child: Padding(
                      padding: EdgeInsets.all(20),
                      child: GestureDetector(
                        onTap: () {
                          Navigator.pushNamed(context, '/' + name);
                        },
                        child: Text(name == 'register' ? '去注册' : '去登陆'),
                      ))),
              SizedBox(
                height: 20,
              ),
              Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(20, 0, 0, 0),
                    child: Text(
                      'Welcome',
                      style: TextStyle(fontSize: 50),
                    ),
                  )),
              Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(20, 0, 0, 0),
                    child: Text('Hencent', style: TextStyle(fontSize: 40)),
                  )),
              Align(
                  alignment: Alignment.centerLeft,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(20, 10, 0, 0),
                    child: Text(
                      '恒创数据中心 讯通节点桥梁',
                      style: TextStyle(color: Colors.white70),
                    ),
                  )),
            ],
          ),
        ),
      ],
    );
  }
}

// 手机号
class InputAdds extends StatefulWidget {
  InputAdds({
    Key? key,
    required this.phones,
    this.callBack,
  }) : super(key: key);
  final callBack;
  String phones;

  @override
  _InputAddsState createState() => _InputAddsState(phones: this.phones);
}

class _InputAddsState extends State<InputAdds> {
  var phones;
  _InputAddsState({this.phones});

  FocusNode phoneFocusNode = FocusNode();
  var phone = new TextEditingController();

  @override
  void initState() {
    phone.text = this.phones;
    // print('this.phones');
  }

  Widget build(BuildContext context) {
    return TextField(
      focusNode: this.phoneFocusNode,
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        hintText: "请输入手机号",
        hintStyle: TextStyle(color: Colors.white70),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white70),
        ),
        prefixIcon: Padding(
          padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Image.asset(
            'assets/img/s1.png',
            width: 20,
            height: 28,
          ),
        ),
        prefixIconConstraints:
            BoxConstraints(//添加内部图标之后，图标和文字会有间距，实现这个方法，不用写任何参数即可解决
                // minHeight: 32,
                // minWidth: 30,
                ),
      ),
      controller: phone,
      onChanged: (value) {
        if (value.length == 11) {
          this.phoneFocusNode.unfocus();
        }
        setState(() {
          phone.text = value;
          widget.callBack(value);
        });
        // print(value);
      },
      maxLength: 11,
    );
  }
}

// 验证码
class InputYzm extends StatefulWidget {
  InputYzm(
      {Key? key,
      required this.phone,
      required this.yzm,
      this.callBack,
      this.callBackId})
      : super(key: key);
  final callBack;
  final callBackId;
  String phone;
  String yzm;

  @override
  _InputYzmState createState() =>
      _InputYzmState(phone: this.phone, yzm: this.yzm);
}

class _InputYzmState extends State<InputYzm> {
  var phone;
  var yzm;
  _InputYzmState({this.phone, this.yzm});

  FocusNode yzmFocusNode = FocusNode();
  var verification = new TextEditingController();
  String buttonText = '获取验证码';
  bool isButtonEnable = true; //按钮状态 是否可点击
  int count = 60;
  late Timer timer; //倒计时的计时器

  @override
  void initState() {
    verification.text = this.yzm;
    // print('this.phone');
    // print(this.phone);
    // print('this.yzm');
    // print(this.yzm);
    // widget.callBack(verification.text);
  }

  // 弹出框
  _toastDialog(String msg) {
    EasyLoading.showToast(msg);
    // EasyLoading.show(status: 'loading...'+msg);
    // EasyLoading.showProgress(0.3, status: 'downloading...');
    // EasyLoading.showSuccess('Great Success!');
    // EasyLoading.showError('Failed with Error');
    // EasyLoading.showInfo('Useful Information.');
    // EasyLoading.showToast(msg);
    // EasyLoading.dismiss();
  }

  void _initTimer() {
    timer = new Timer.periodic(Duration(seconds: 1), (Timer timer) {
      count--;
      setState(() {
        if (count == 0) {
          timer.cancel();
          isButtonEnable = true;
          count = 60;
          buttonText = "获取验证码";
        } else {
          buttonText = "${count}s";
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      keyboardType: TextInputType.number,
      focusNode: this.yzmFocusNode,
      // autofocus: false,
      decoration: InputDecoration(
        hintText: "请输入验证码",
        hintStyle: TextStyle(color: Colors.white70),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white70),
        ),
        prefixIcon: Padding(
          padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Image.asset(
            'assets/img/s2.png',
            width: 20,
            height: 28,
          ),
        ),
        prefixIconConstraints: BoxConstraints(),
        suffixIcon: SizedBox(
          width: 105,
          height: 30,
          child: OutlinedButton(
            // borderSide:BorderSide(color: Color(0xff17E2E4)),
            style: ButtonStyle(
                side: MaterialStateProperty.all(
                    BorderSide(color: Color(0xff17E2E4)))),
            onPressed: () {
              print(phone);
              this.yzmFocusNode.unfocus();
              Future.delayed(Duration(milliseconds: 500), () {
                this.yzmFocusNode.unfocus();
              });

              if (verification.text.length != 4) {
                _toastDialog("请输入四位数验证码");
                return;
              }
              //点击验证码
              setState(() {
                // 是否能够点击
                if (isButtonEnable) {
                  EasyLoading.show(status: 'loading...');
                  print(phone);
                  HttpUtil().postHttp(
                    "/tbr/sendMessage",
                    parameters: {'phone': phone},
                    onSuccess: (Map res) {
                      print(res);
                      if (res['code'] == '200') {
                        EasyLoading.dismiss();
                        widget.callBackId(res['data']['sessionId']);
                        _initTimer();
                      }
                    }
                  );
                  return null;
                } else {
                  return null;
                }
              });
              // _initTimer();
            },
            child: Text(
              this.buttonText,
              style: TextStyle(color: Color(0xff17E2E4)),
            ),
          ),
        ),
        suffixIconConstraints: BoxConstraints(),
      ),
      controller: verification,
      onChanged: (value) {
        // print(value);
        if (value.length == 4) {
          this.yzmFocusNode.unfocus();
        }
        setState(() {
          verification.text = value;
          widget.callBack(value);
        });
        // print(value);
      },
      maxLength: 4,
    );
  }
}

// 协议
class Protocol extends StatefulWidget {
  Protocol({Key? key, this.callBack}) : super(key: key);
  final callBack;

  @override
  _ProtocolState createState() => _ProtocolState();
}

class _ProtocolState extends State<Protocol> {
  var flag = true;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: [
          Container(
            width: 20,
            height: 20,
            margin: EdgeInsets.fromLTRB(0, 0, 5, 0),
            padding: EdgeInsets.all(0),
            decoration: BoxDecoration(
                border: Border.all(
                    color: flag ? Color(0xff17E2E4) : Color(0xff7886B0),
                    width: 1.5),
                // color: Colors.blue,
                borderRadius: BorderRadius.circular(60)),
            child: Theme(
              data: ThemeData(
                  // unselectedWidgetColor: Color(0xff7886B0)
                  ),
              child: Checkbox(
                tristate: false,
                shape: CircleBorder(),
                value: this.flag,
                onChanged: (val) {
                  setState(() {
                    this.flag = val!;
                    widget.callBack(val);
                  });
                  // print(val);
                },
                checkColor: Color(0xff17E2E4),
                activeColor: Color(0xff040F22),
              ),
            ),
          ),
          Text(
            '开启即代表同意',
            style: TextStyle(color: Colors.white70),
          ),
          Text(
            '《用户注册协议》',
            style: TextStyle(color: Color(0xff17E2E4)),
          ),
          Text(';'),
        ],
      ),
    );
  }
}

class OnButton extends StatefulWidget {
  OnButton({Key? key, this.name, this.callBack}) : super(key: key);
  final callBack;
  var name;

  @override
  _OnButtonState createState() => _OnButtonState(name: this.name);
}

class _OnButtonState extends State<OnButton> {
  var name;
  _OnButtonState({this.name});
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all(Color(0xff00B1F2))),
        onPressed: () {
          widget.callBack();
        },
        child: Text(
          name,
          style: TextStyle(fontSize: 18),
        ));
  }
}

// 邀请码
class InputInvite extends StatefulWidget {
  InputInvite({
    Key? key,
    required this.invites,
    this.callBack,
  }) : super(key: key);
  final callBack;
  String invites;

  @override
  _InputInviteState createState() => _InputInviteState(invites: this.invites);
}

class _InputInviteState extends State<InputInvite> {
  var invites;
  _InputInviteState({this.invites});

  FocusNode inviteFocusNode = FocusNode();
  var invite = new TextEditingController();

  @override
  void initState() {
    invite.text = this.invites;
    // print('this.phones');
  }

  Widget build(BuildContext context) {
    return TextField(
      focusNode: this.inviteFocusNode,
      keyboardType: TextInputType.text,
      decoration: InputDecoration(
        hintText: "请输入邀请码",
        hintStyle: TextStyle(color: Colors.white70),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white70),
        ),
        prefixIcon: Padding(
          padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Image.asset(
            'assets/img/s3.png',
            width: 20,
            height: 28,
          ),
        ),
        prefixIconConstraints:
            BoxConstraints(//添加内部图标之后，图标和文字会有间距，实现这个方法，不用写任何参数即可解决
                // minHeight: 32,
                // minWidth: 30,
                ),
      ),
      controller: invite,
      onChanged: (value) {
        if (value.length == 5) {
          this.inviteFocusNode.unfocus();
        }
        setState(() {
          invite.text = value;
          widget.callBack(value);
        });
        // print(value);
      },
      maxLength: 11,
    );
  }
}
